# -*- coding:utf8 -*-
__author__ = 'Administrator'

from conf import *
import struct
import socket, time
import platform
if platform.system() == "Windows":
    import win32ras


class Logger():
        def Logger(self,level,message):
            try:
                if level == "INFO":
                    print(time.strftime(ISOTIMEFORMAT,time.localtime())+"   [INFO]   "+message)
                elif level == "ERROR":
                    print(time.strftime(ISOTIMEFORMAT,time.localtime())+" [ERROR]  "+message)
                elif level == "WARNING":
                    print(time.strftime(ISOTIMEFORMAT,time.localtime())+" [WARNING]"+message)
            except Exception,e:
                print(str(Exception)+"   "+str(e))

# class Srun_Linux(Logger):
#     def __init__(self):
#         self.username = ""
#         self.result = ""
#         self.handle = ""


class Srun_Windows(Logger):
    def __init__(self):
        self.username = "{SRUN2}"
        self.result = ""
        self.handle = ""
        self.__ChangeUserName()
        self.handle,self.result = self.__DialBroadband()

    def __ChangeUserName(self):
        for each in USERNAME:
            self.username += chr(ord(each)+4)
        self.Logger("INFO","Username encode successful")

    def __Connection(self,dialog_name, account, password):
        dial_params = (dialog_name, '', '', account, password, '')
        return win32ras.Dial(None, None, dial_params, None)

    def __DialBroadband(self):
        dialname = "SRun3K专用宽带拨号连接"
        try:
            handle, result = self.__Connection(dialname, self.username, PASSWORD)
            if result == 0:
                self.Logger("INFO","Connection success!")
                return handle, result
            else:
                self.Logger("INFO","Connection failed, wait for 5 seconds and try again..."+self.username)
                time.sleep(5)
                self.__DialBroadband()
        except:
            self.Logger("INFO","Can't finish this connection, please check out.")
            return 0

    def Disconnect(self,handle):
        if handle != None:
            try:
                win32ras.HangUp(handle)
                self.Logger("INFO","Disconnection success!")
                return "success"
            except:
                self.Logger("INFO","Disconnection failed, wait for 5 seconds and try again...")
                time.sleep(5)
                self.Disconnect(handle)
        else:
            self.Logger("INFO","Can't find the process!")
            return 0

    def Check_for_Broadband(self):
        connections = win32ras.EnumConnections()
        if(len(connections) == 0):
            self.Logger("INFO","The system is not running any broadband connection.")
            return 0
        else:
            self.Logger("INFO","The system is running %d broadband connection." % len(connections))
            return connections

class Srun(Logger):
    def __init__(self):
        myname = socket.getfqdn(socket.gethostname())
        myaddr = socket.gethostbyname(myname)
        values = ('CHECK_VERSION',"",117,int(str(myaddr).split(".")[0]),int(str(myaddr).split(".")[1]),int(str(myaddr).split(".")[2]),int(str(myaddr).split(".")[3]))
        s = struct.Struct("13s39siBBBB")
        self.heart_packet= s.pack(*values)
        if platform.system() == "Windows":
            self.srun = Srun_Windows()
        if self.srun.result == 0:
            self.__Send_Heartbeat_Packet()
        # elif platform.system() == "Linux":
        #     self.srun = Srun_Linux()

    def __Send_Heartbeat_Packet(self):
        if self.srun.result == 0:
            self.Logger("INFO","Sending heartbeat to IP %s , port %d" % (SERVER_IP, SERVER_PORT))
            while True:
                hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                hbSocket.sendto(self.heart_packet, (SERVER_IP, SERVER_PORT))
                time.sleep(BEAT_PERIOD)

srun = Srun()